<?php
/**
 * User: 五哥派
 * Date: 2024/7/1
 * Tel(同WX): 17335592719
 */
namespace app\api\model\dealer;

use app\api\model\Base;

use app\common\enum\dealer\apply\ApplyStatus as ApplyStatusEnum;
use app\common\enum\dealer\apply\ApplyType as ApplyTypeEnum;
use think\db\exception\DbException;

class Apply extends Base{

    protected $name = 'dealer_apply';


    /**
     * 自动提交分销申请
     * @param array $data
     * @return mixed
     * @throws DbException
     */
    public function autoOpen(array $data)
    {
        // 成为分销商条件
        $config = Setting::getItem('condition');

        $data = [
            'user_id' => $data['user_id'],
            'name' => trim($data['name']),
            'mobile' => trim($data['mobile']),
            'referee_id' => Referee::getRefereeUserId($data['user_id'], 1),
            'apply_type' => $config['become'],
            'apply_time' => time(),
        ];
        //10 需后端审核  20 不需后端审核，直接通过
        if ($config['become'] == 10) {
            $data['apply_status'] = 10; // 10 待审
        } elseif ($config['become'] == 20) {
            $data['apply_status'] = 20; //审核通过
        }
        return $this->autoAdd($data);
    }



    /**
     * 分销申请自动审核通过
     * @param array $data
     * @return mixed
     */
    private function autoAdd(array $data)
    {
        // 当前用户ID
        $userId = $data['user_id'];
        // 实例化模型
        $model = self::detail(['user_id' => $userId]) ?: $this;
        // 更新记录
        return $this->transaction(function () use ($model, $userId, $data) {
            // 保存申请信息
            $model->save($data);
            // 20无需审核，自动通过
            if ($data['apply_type'] == 20) {
                // 新增分销商用户记录
                User::add($userId, [
                    'real_name' => $data['real_name'],
                    'mobile' => $data['mobile'],
                    'referee_id' => $data['referee_id']
                ]);
            }
            return true;
        });
    }

}